/*
 * @Author: 阿芙
 * @Date: 2021-06-14 14:19:48
 * @LastEditTime: 2021-08-28 21:39:43
 * @LastEditTime: 2021-06-25 22:14:28
 * @LastEditors: Please set LastEditors
 * @Description: 用于向外抛出方法
 * @FilePath: /RuoLing-SQL/lib/MYSQL.js
 */


//处理SQL方法
const MYSQLDB = require("./MYSQLDB.js");


/**
 * @description: 外部使用
 * @param {*} config
 * @return {*}
 */
function MYSQL(config){
    "use strict";
    let _this = this;
    _this.config = config;
 
    _this.MYSQLDB = null;

    _this.Init();
};

/**
 * @description: 初始化配置
 * @param {*}
 * @return {*}
 */
MYSQL.prototype.Init = function (){
    "use strict";
    let _this = this;
    _this.MYSQLDB = new MYSQLDB(_this.config);
   
};


/**
 * @description: 开启连接
 * @param {*}
 * @return {*}
 */
MYSQL.prototype.connect = function(){
    "use strict";
    let _this = this;
    return new Promise((resolve,reject)=>{
        _this.MYSQLDB.queryConnection().then((conn)=>{
            //创建存储连接
           const connection = new Connection(conn);
            //connect 方法
            resolve(connection);
           // return;
        }).catch((error)=>{

            reject(error);
            return;
        });
    });
};





/**
 * @description: 存储连接 ,向外抛出连接方法,这个地方是每次开启连接，创建一次连接对象存储，为了保证并发问题
 * @param {*}
 * @return {*}
 */
function Connection(conn){
    "use strict";
    let _this = this;
    _this.connection=conn;
    _this.message = null;
    _this.startTrans_State = false; //没有开启事务
    _this.Connection_Init();
};



Connection.prototype.Connection_Init = function(){
    "use strict";
    this.message = "连接创建成功"
};





/**
 * @description: 开启连接之后，执行SQL，并返回数据，且没有关闭连接
 * @param {*} sql
 * @return {*}
 */
Connection.prototype.connect_query = function(sql,param) {
    "use strict";
    let _this = this;
    return new Promise((resolve,reject)=>{
        if(Array.isArray(param)){
            //预防SQL注入
            _this.connection.query(sql,param,(err,result)=>{
                if(err){
                    _this.connection.release();
                    reject(err);
                    return;
                }
                    resolve(result);
                    return;
            });
            
        }else{

            _this.connection.query(sql,(err,result)=>{
                if(err){
                    _this.connection.release();
                    reject(err);
                    return;
                }
                    resolve(result);
                    return;
            });
        }
       
    });
};

/**
 * @description: 报错关闭连接
 * @param n*o
 * @return n*o
 */
Connection.prototype.close = function(){
    "use strict";

    let _this = this;
    _this.connection.release();
    return;
}



/**
 * @description: 开启连接，执行SQL，并且返回数据，关闭连接
 * @param {*} sql
 * @return {*}
 */
 Connection.prototype.connect_query_close = function (sql,param) {
    "use strict";
    let _this = this;

    return new Promise((resolve,reject)=>{
        
        if(Array.isArray(param)){
            //预防SQL注入
            _this.connection.query(sql,param,(err,result)=>{
                if(err){
                    _this.connection.release();
                    reject(err);
                    return;
                }
                    _this.connection.release();
                    resolve(result);
                    return;
            });

        }else{

            _this.connection.query(sql,(err,result)=>{
                if(err){
                    _this.connection.release();
                    reject(err);
                    return;
                }
                    _this.connection.release();
                    resolve(result);
                    return;
            });
        }
       
    });
};

/**
 * @description: 启动事务
 * @param {*}
 * @return {*}
 */
Connection.prototype.startTrans = function () {
    "use strict";
     let _this = this;
     if(_this.connection != null){
        return new Promise((resolve,reject)=>{
            _this.connect_query("START TRANSACTION").then((data)=>{
                //事务状态
                _this.startTrans_State = true;
                let obj = {
                    "commit":_this.commit.bind(_this),
                    "rollback":_this.rollback.bind(_this),
                    "query":_this.query.bind(_this),
                };
                resolve(obj);
                return;
            }).catch((error)=>{
                reject(error);
                return;
            });
        })
     }else{
         throw new Error("connection not null");
     }
};

/**
 * @description: 事务提交
 * @param {*}
 * @return {*}
 */
Connection.prototype.commit = function(){
    "use strict";

    let _this = this;
    if(_this.startTrans_State){
        return new Promise((resolve,reject)=>{
            _this.query("COMMIT").then((data)=>{
                _this.connection.release();
                resolve("事务提交成功");
                return;
               
            }).catch((err)=>{
                _this.connection.release();
                reject(err);
                return;
            });
        });
    }else{
        throw new Error("startTrans_State not false");
    }
};


/**
 * @description: 事务回滚
 * @param {*}
 * @return {*}
 */
Connection.prototype.rollback = function(){
    "use strict";
    let _this = this;
    if(_this.startTrans_State){
        return new Promise((resolve,reject)=>{
            _this.query("ROLLBACK").then((data)=>{
                _this.connection.release();
                resolve("事务回滚成功");
                return;
               
            }).catch((err)=>{
                _this.connection.release();
                reject(err);
                return;
            });
        });
    }else{
        throw new Error("startTrans_State not false");
    }
};


/**
 * @description:开启事务，需要执行SQL ，这里面不处理连接关闭 
 * @param {*} sql
 * @return {*}
 */
Connection.prototype.query = function (sql,param) {
    "use strict";
    let _this = this;
    
    if(_this.startTrans_State){
        return new Promise((resolve,reject)=>{

            if(Array.isArray(param)){
                if(_this.config.log == "debug"){
                    console.log(sql/n)
                    console.log(param/n)
                }
                //预防SQL注入
                _this.connection.query(sql,param,(err,result)=>{
                    if(err){
                        reject(err);
                        return;
                    }
                        resolve(result);
                        return;
                });
            }else{
                if(_this.config.log == "debug"){
                    console.log(sql/n)
                }
                _this.connection.query(sql,(err,result)=>{
                    if(err){
                        reject(err);
                        return;
                    }
                        resolve(result);
                        return;
                });
            }
            
        });
    }else{
        throw new Error("startTrans_State not false");
    }
};




module.exports = MYSQL;

/**
 * 
 * 
 * 我需要简单的使用 数据连接池
 * 
 * connection = null;
 * connection.query("")
 */


let config = {
    host:"192.168.50.128",
    user:"root",
    password:"lvdi123",
    database:"ruoling_test",
    connectionLimit : 2,
}


// let my = new MYSQL(config);

// async function tt(){

//     let connect = await my.connect();
//        // console.log(connect)
      
//     for(let i = 0;i<12;i++){
        
//        console.log( await connect.connect_query("select * from sys_user"))
//     }
    
// }

// function tt(){
//     my.connect().then((conn)=>{
//         // conn.connect_query_close("select * from sys_user").then((data)=>{
//         //     console.log(data)
//         // })
     
//     })
// }

//tt()


